import 'package:built_collection/built_collection.dart';
import 'package:equatable/equatable.dart';
import 'package:mobile_app/app/domain/repositories/asset_learning_content_repository/repository.dart';
import 'package:mobile_app.core/core/domain/entities/asset/asset_collection_list_item.dart';
import 'package:mobile_app.core/core/domain/entities/asset/asset_dialect.dart';
import 'package:mobile_app.core/core/domain/entities/asset/asset_lexical_item_use_case.dart';
import 'package:mobile_app.core/core/domain/entities/asset/asset_lexical_items.dart';
import 'package:mobile_app.core/core/domain/stores/asset_store/store.dart';

part 'dtos/adjective_dto.dart';

part 'dtos/adverb_dto.dart';

part 'dtos/collection_dto.dart';

part 'dtos/collection_folder_dto.dart';

part 'dtos/collection_list_item_dto.dart';

part 'dtos/collection_list_item_dto_factory.dart';

part 'dtos/conjunction_dto.dart';

part 'dtos/dialect_dto.dart';

part 'dtos/lexical_item_dto.dart';

part 'dtos/lexical_item_dto_factory.dart';

part 'dtos/noun_dto.dart';

part 'dtos/numeral_dto.dart';

part 'dtos/phrasal_verb_dto.dart';

part 'dtos/preposition_dto.dart';

part 'dtos/pronoun_dto.dart';

part 'dtos/use_case_dto.dart';

part 'dtos/verb_dto.dart';

part 'dtos/word_dto.dart';

const _kVersionKey = 'version';
const _kLexicalItemKey = 'lexical_items';
const _kCollectionListItemKey = 'collection_list_items';

class AssetLearningContentRepositoryImpl implements AssetLearningContentRepository {
  const AssetLearningContentRepositoryImpl({
    required AssetStore store,
  }) : _store = store;

  final AssetStore _store;

  @override
  Future<int> getVersion() async {
    final version = await _store.get(
      key: _kVersionKey,
    ) as int;

    return version;
  }

  @override
  Future<BuiltList<AssetLexicalItem>> getLexicalItems() async {
    final data = await _store.get(
      key: _kLexicalItemKey,
    );

    final lexicalItemMaps = List.castFrom<dynamic, Map>(data);

    final lexicalItems = lexicalItemMaps.map((lexicalItemMap) {
      final lexicalItemJson = Map.castFrom<dynamic, dynamic, String, dynamic>(lexicalItemMap);

      final lexicalItemDto = _LexicalItemDtoFactory().fromJson(lexicalItemJson);

      return lexicalItemDto.toEntity();
    }).toBuiltList();

    return lexicalItems;
  }

  @override
  Future<BuiltList<AssetCollectionListItem>> getCollectionListItems() async {
    final data = await _store.get(
      key: _kCollectionListItemKey,
    );

    final collectionListItemMaps = List.castFrom<dynamic, Map>(data);

    final collectionListItems = collectionListItemMaps.map((collectionListItemMap) {
      final collectionListItemJson =
          Map.castFrom<dynamic, dynamic, String, dynamic>(collectionListItemMap);

      final collectionListItemDto =
          _CollectionListItemDtoFactory().fromJson(collectionListItemJson);

      return collectionListItemDto.toEntity();
    }).toBuiltList();

    return collectionListItems;
  }
}
